package com.wkr.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wkr.common.Constants;
import com.wkr.order.dao.TrainStoreDao;
import com.wkr.order.entity.TrainStoreEntity;
import com.wkr.order.service.IStoreService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Optional;

@Service
@Slf4j
public class TrainStoreServiceImpl implements IStoreService {

    @Resource
    private TrainStoreDao trainStoreDao;

    @Override
    @Transactional
    public void update() {
        log.info("XID: "+ RootContext.getXID());
        Optional<TrainStoreEntity> data = trainStoreDao.findById(Constants.TRAIN_STORE_TYPE);
        Long leftCount;
        if (!data.isPresent()) {
            TrainStoreEntity trainStoreEntity = new TrainStoreEntity();
            trainStoreEntity.setTrainStoreId(Constants.TRAIN_STORE_TYPE);
            trainStoreEntity.setCount(99L);
            trainStoreEntity.setCreateTime(LocalDateTime.now());
            trainStoreEntity.setUpdateTime(LocalDateTime.now());
            trainStoreDao.save(trainStoreEntity);
            leftCount = 98L;
        } else {
            log.info("库存数据:{}", JSONObject.toJSONString(data.get()));
            leftCount = data.get().getCount() - 1;
        }

        trainStoreDao.updateCountById(leftCount, LocalDateTime.now());
    }
}
